<?php

namespace apiend\modules\statistic\models;

use Yii;

/**
 * 商品排行榜
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class RankGoodsSearch extends \common\models\shop\ShopOrderGoods {

    use \common\logics\stats\TimefilterTrait;

    /**
     * @var bool 不使用分页
     */
    public $pagesize = false;

    /**
     * @var integer 限制读取条数
     */
    public $limitSize = 30;

    /**
     * @var bool 不使用分页
     */
    public $amount;

    /**
     * @var bool 不使用分页
     */
    public $sales;

    /**
     * {@inheritdoc}
     */
    public function buildQuery() {
        $query = static::find()->alias('t')->active();
        $query->innerJoinWith('order order');
        $query->andFilterDuration('order.pay_time', $this->beginTime, $this->endTime);
        $query->select([
            '*',
            'amount' => 'sum(t.goods_price*t.goods_number-t.goods_discount)',
            'sales' => 'sum(t.goods_number)',
        ]);
        $query->groupBy([
            't.product_id'
        ]);
        $query->orderBy([
            'sales' => SORT_DESC
        ]);
        return $query;
    }

    /**
     * {@inheritdoc}
     */
    public function search($params = []) {
        if (!$this->validate()) {
            return [];
        }
        return parent::search($params);
    }

    public function fields() {
        return [
            'id',
            'name',
            'amount',
            'sales',
        ];
    }

}
